package com.huidz.calendar.mainfragment;

import android.app.ActivityOptions;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huidz.calendar.R;
import com.huidz.calendar.activity.BeiWangLuActivity;
import com.huidz.calendar.activity.JiNianRiActivity;
import com.huidz.calendar.activity.ShengRiActivity;
import com.huidz.calendar.activity.SubmitActivity;
import com.huidz.calendar.activity.SystemActivity;
import com.huidz.calendar.activity.User_LoginActivity;
import com.huidz.calendar.model.CheckheadModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.Url;
import com.huidz.calendar.view.RoundImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CenterFragment extends Fragment implements View.OnClickListener {
    //用于获取视图
    private View root;
    private RoundImageView user_head;
    private ImageView bianji;
    private TextView no_login, user_name, user_token;

    private int login_id = 0;//默认为0，表示没有登录，不等于0表示登录

    private RelativeLayout wdbwl, wdsr, wdjnr, wdsc, set, wdfk, wdtj, wdpj, wdbb, now_login;

    private TextView bbh;
    public boolean sag = false;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_me, container, false);//初始加载
            initView(root);
        return root;
    }

    public boolean loding = false;

    @Override
    public void onResume() {
        super.onResume();
        if (!Url.USER_NAME.equals("")) {
            login_id = 1;
            Apiutils.GET_IMAGE(getActivity(), Url.USER_HEAD, user_head);
            user_name.setText(Url.USER_NAME);
            Visbview(login_id);
        } else {
            login_id = 0;
            Glide.with(getActivity())
                    .load(R.mipmap.no_login)
                    .into(user_head);
            user_name.setText("请登录");
            Visbview(login_id);
        }

    }

    /**
     * 初始加载视图
     */
    public void initView(View view) {
        user_head = view.findViewById(R.id.user_head);
        user_head.setOnClickListener(this);
        now_login = view.findViewById(R.id.now_login);
        now_login.setOnClickListener(this);
        bianji = view.findViewById(R.id.bianji);
        no_login = view.findViewById(R.id.no_login);
        user_name = view.findViewById(R.id.user_name);
        user_token = view.findViewById(R.id.user_token);
        wdbwl = view.findViewById(R.id.wdbwl);
        wdbwl.setOnClickListener(this);
        wdsr = view.findViewById(R.id.wdsr);
        wdsr.setOnClickListener(this);
        wdjnr = view.findViewById(R.id.wdjnr);
        wdjnr.setOnClickListener(this);
        wdsc = view.findViewById(R.id.wdsc);
        wdsc.setOnClickListener(this);
        set = view.findViewById(R.id.set);
        set.setOnClickListener(this);
        wdfk = view.findViewById(R.id.wdfk);
        wdfk.setOnClickListener(this);
        wdtj = view.findViewById(R.id.wdtj);
        wdtj.setOnClickListener(this);
        wdpj = view.findViewById(R.id.wdpj);
        wdpj.setOnClickListener(this);
        wdbb = view.findViewById(R.id.wdbb);
        wdbb.setOnClickListener(this);
        bbh = view.findViewById(R.id.bbh);
        Visbview(login_id);
    }

    public void Visbview(int index) {
        switch (index) {
            case 0:
                no_login.setVisibility(View.VISIBLE);
                bianji.setVisibility(View.GONE);
                user_name.setVisibility(View.GONE);
                user_token.setVisibility(View.GONE);
                break;
            case 1:
                no_login.setVisibility(View.GONE);
                bianji.setVisibility(View.VISIBLE);
                user_name.setVisibility(View.VISIBLE);
                user_token.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.wdbwl:
                if (Url.USER_TOKEN.equals(""))
                    Apiutils.SetToast(getActivity(), "请先登录");
                else {
                    Intent tobwl = new Intent(getActivity(), BeiWangLuActivity.class);
                    startActivity(tobwl, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                }
                break;
            case R.id.wdsr:
                if (Url.USER_TOKEN.equals(""))
                    Apiutils.SetToast(getActivity(), "请先登录");
                else {
                    Intent tosr = new Intent(getActivity(), ShengRiActivity.class);
                    startActivity(tosr, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                }
                break;
            case R.id.wdjnr:
                if (Url.USER_TOKEN.equals(""))
                    Apiutils.SetToast(getActivity(), "请先登录");
                else {
                    Intent tojnr = new Intent(getActivity(), JiNianRiActivity.class);
                    startActivity(tojnr, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                }
                break;
            case R.id.wdsc:

                break;
            case R.id.set:
                Intent toset = new Intent(getActivity(), SystemActivity.class);
                startActivity(toset, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                break;
            case R.id.wdfk:
                if (Url.USER_TOKEN.equals(""))
                    Apiutils.SetToast(getActivity(), "请先登录");
                else {
                    Intent tofk = new Intent(getActivity(), SubmitActivity.class);
                    startActivity(tofk, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                }
                break;
            case R.id.wdtj:
                Apiutils.Share_wx(getActivity(), Url.fenxiang_shareapp, Url.fenxiang_title, Url.fenxiang_image, Url.fenxiang_url2);
                break;
            case R.id.wdpj:

                break;
            case R.id.wdbb:
                break;
            case R.id.user_head:
                if (login_id == 1) {
                    Intent intents = new Intent(Intent.ACTION_PICK, null);
                    intents.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intents, 2);
                }
                break;
            case R.id.now_login:
                if (login_id == 0) {
                    Intent intent = new Intent(getActivity(), User_LoginActivity.class);
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(getActivity()).toBundle());
                } else {

                }
                break;
        }
    }

    String url;

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            if (data != null) {
                String encode = null;
                // 得到图片的全路径
                Uri uri = data.getData();
                user_head.setImageURI(uri);
                url = uri.toString();
                Apiutils.GET_IMAGE(getActivity(), url, user_head);
                //调用URL转file方法
                File file = uri2File(uri);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picPath = cursor.getString(columnIndex);
                //转码
                try {
                    encode = URLEncoder.encode(picPath, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                cursor.close();
                if (picPath.equals("")) return;
//                Apiutils.SetLog("url:" + encode);
//                okHttp_postFromParameters(encode)
                postfiles(file);
            }
        }
    }

    public void okHttp_postFromParameters(String file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("avatar", file + "").add("logintoken", Url.USER_TOKEN)
                            .build();
                    Request request = new Request.Builder().url(Url.UPDATEHEAD).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Apiutils.SetToast(getActivity(), msgs + "");
                    } else
                        Apiutils.SetToast(getActivity(), msgs + "");
                }

            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    public void postfile(File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
                    RequestBody requestBody = new MultipartBody.Builder()
                            .setType(MultipartBody.ALTERNATIVE)
                            .addFormDataPart("logintoken", Url.USER_TOKEN)
                            .addFormDataPart("avatar", file.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                            .build();
                    Request request = new Request.Builder()
                            .url(Url.UPDATEHEAD)
                            .post(requestBody)
                            .build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void postfiles(File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                post_file(Url.UPDATEHEAD, file);
            }
        }).start();
    }

    protected void post_file(final String url, File file) {
        OkHttpClient client = new OkHttpClient();
//        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        requestBody.addFormDataPart("avatar", file.getName(), body);
        requestBody.addFormDataPart("logintoken", Url.USER_TOKEN);
        Apiutils.setlog(requestBody.toString());
        Request request = new Request.Builder().url(url).post(requestBody.build()).tag(getActivity()).build();
        client.newBuilder().readTimeout(5000, TimeUnit.MILLISECONDS).build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String str = response.body().string();
                    JSONObject success_Object = null;
                    try {
                        success_Object = new JSONObject(str);
                        String code = success_Object.getString("code");
                        if (code.equals("1")) {
                            Gson gson = new Gson();
                            CheckheadModel userms = gson.fromJson(str,
                                    CheckheadModel.class);
                            Url.USER_HEAD = userms.getMsg().getAvatar();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    Apiutils.setlog(response.message() + " error : body " + response.body().string());
                }
            }
        });
    }

//    public void texdtman() {
//        List<Part> partList = new ArrayList<Part>();
//        partList.add(new StringPart("title", title, "UTF-8"));
//        partList.add(new FilePart("image[]", image[i]));
//        VolleyUtils.getInstance().requestPostUploadParams(requestType, Config.PUBLISH_ARTICLE, callback, partList);
//    }
}
